package com.sense.kukoo.common.wiget

import android.content.Context
import android.util.AttributeSet
import android.widget.FrameLayout
import android.widget.TextView
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import androidx.cardview.widget.CardView
import com.alibaba.android.arouter.launcher.ARouter
import com.google.android.material.progressindicator.CircularProgressIndicator
import com.sense.kukoo.common.R
import com.sense.kukoo.common.constant.ARouterUrl
import com.sense.kukoo.common.media.Kukoo
import com.sense.kukoo.common.media.bean.LocalMediaListItemBean
import com.sense.kukoo.common.media.watcher.UserWatcher
import com.sense.kukoo.lib_picture.loader.Monet
import com.sense.kukoo.common.utils.ApplicationContext
import com.sense.kukoo.lib_logger.LoggerManager

class MusicPlayerView : FrameLayout, View.OnClickListener {

    private val TAG = MusicPlayerView::class.java.simpleName

    private lateinit var mIcon: ImageView
    private lateinit var mCardView: CardView
    private lateinit var mBtnList: ImageView
    private lateinit var mBtnPlay: ImageView
    private lateinit var mBtnProgress: CircularProgressIndicator
    private lateinit var mName: TextView
    private lateinit var mTimer: TextView
    private lateinit var ll_title_and_time: View

    private var state = UserWatcher.MusicStateWatcher.STATE_NOT_PLAYING
    private var mCurrentMusic: LocalMediaListItemBean? = null

    constructor(context: Context) : super(context) {
        initView()
    }

    constructor(context: Context, attrs: AttributeSet?) : super(context, attrs) {
        initView()
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        initView()
    }

    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) {
        initView()
    }

    private fun initView() {
        LayoutInflater.from(context).inflate(R.layout.common_music_player, this, true)
        //
        mIcon = findViewById(R.id.music_player_view_icon)
        mCardView = findViewById(R.id.card_view)
        mBtnList = findViewById(R.id.music_player_view_list)
        mBtnPlay = findViewById(R.id.music_player_view_btn_play)
        mBtnProgress = findViewById(R.id.music_player_view_btn_progress)
        mName = findViewById(R.id.music_player_view_name)
        mTimer = findViewById(R.id.music_player_view_timer)
        ll_title_and_time = findViewById(R.id.ll_title_and_time)
        //
        mCardView.setOnClickListener(this)
        mBtnList.setOnClickListener(this)
        mBtnPlay.setOnClickListener(this)
        ll_title_and_time.setOnClickListener(this)
    }

    fun setCoverUrl(url: String?) {
        Monet.get(ApplicationContext.instance())
            .load<Any>(url)
            .placeholder(R.mipmap.common_icon_default_editor_picks)
            .into(mIcon)
    }

    fun setName(s: String?) {
        mName.text = s
    }

    fun setTime(s: String?) {
        mTimer.text = s
    }

    override fun onClick(v: View) {
        val id = v.id
        if (id == R.id.card_view) {
            showMediaControler()
        } else if (id == R.id.ll_title_and_time) {
            showMediaControler()
        } else if (id == R.id.music_player_view_list) {
            showMediaList()
        } else if (id == R.id.music_player_view_btn_play) {
            onBtnPlayClick()
        }
    }

    private fun showMediaControler() {
        mCurrentMusic?.data?.let { data ->
            ARouter.getInstance()
                .build(ARouterUrl.ROUTE_MEDIA_MODULE_MEDIA_DESCRIPTION_ACTIVITY)
                .withString(ARouterUrl.KEY_FROM, "${data.id}")
                .navigation()
        }
    }

    private fun showMediaList() {
        ARouter.getInstance()
            .build(ARouterUrl.ROUTE_MEDIA_MODULE_MEDIA_LIST_ACTIVITY)
            .navigation()
    }

    private fun onBtnPlayClick() {
        when (state) {
            UserWatcher.MusicStateWatcher.STATE_PREPARE,
            UserWatcher.MusicStateWatcher.STATE_ERROR_RETRYING,
            UserWatcher.MusicStateWatcher.STATE_SEEKING,
            UserWatcher.MusicStateWatcher.STATE_PLAYING ->{
                Kukoo.input.pause()
            }
            UserWatcher.MusicStateWatcher.STATE_PAUSE ->{
                Kukoo.input.start()
            }
            else ->{
                LoggerManager.e(TAG, "onBtnPlayClick() state=${state}, 不响应")
            }
        }
    }

    private val mlistener = object : UserWatcher.MusicStateWatcher {

        override fun onMusicChanged(music: LocalMediaListItemBean) {
            mCurrentMusic = music
            setCoverUrl(music.coverOfChapter())
            setName(music.titleOfChapter())
        }

        override fun onPlayTimeChanged(currentInt: Int, totalInt: Int, current: String, total: String) {
            setTime("${current}/${total}")
        }

        override fun onPlayPercentChanged(percent: Int) {
            mBtnProgress.progress = percent
        }

        override fun onPlayStateChanged(s: Int) {
            state = s
            when (state) {
                UserWatcher.MusicStateWatcher.STATE_NOT_PLAYING ->{
                    mBtnProgress.visibility = View.INVISIBLE
                    mBtnPlay.setImageResource(R.drawable.common_icon2_stop_gray)
                    mName.text = ApplicationContext.getString(com.sense.kukoo.common_i18n.R.string.media_player_not_playing)
                    Monet.get(ApplicationContext.instance())
                        .load<Any>(R.mipmap.common_icon_app_for_player)
                        .placeholder(R.mipmap.common_icon_default_editor_picks)
                        .into(mIcon)
                }
                UserWatcher.MusicStateWatcher.STATE_ERROR_RETRYING,
                UserWatcher.MusicStateWatcher.STATE_PREPARE,
                UserWatcher.MusicStateWatcher.STATE_SEEKING,
                UserWatcher.MusicStateWatcher.STATE_PLAYING ->{
                    mBtnProgress.visibility = View.VISIBLE
                    mBtnPlay.setImageResource(R.drawable.common_icon2_pause_progress)
                }
                UserWatcher.MusicStateWatcher.STATE_PAUSE ->{
                    mBtnProgress.visibility = View.VISIBLE
                    mBtnPlay.setImageResource(R.drawable.common_icon2_play_progress)
                }
                else ->{}
            }
            if (state == UserWatcher.MusicStateWatcher.STATE_NOT_PLAYING) {
                mBtnPlay.isEnabled = false
                mCardView.isEnabled = false
                mName.isEnabled = false
                mTimer.isEnabled = false
                ll_title_and_time.isEnabled = false
                //setShowOrHide(false)
            } else {
                mBtnPlay.isEnabled = true
                mCardView.isEnabled = true
                mName.isEnabled = true
                mTimer.isEnabled = true
                ll_title_and_time.isEnabled = true
                //setShowOrHide(true)
            }
        }

        override fun onPlaySpeedChanged(speed: Float) {}

        override fun onPlayListChanged() {}
    }

    override fun onAttachedToWindow() {
        super.onAttachedToWindow()
        Kukoo.watcher.register(mlistener)
    }

    override fun onDetachedFromWindow() {
        super.onDetachedFromWindow()
        Kukoo.watcher.unregister(mlistener)
    }

}